import 'dart:io';

import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_news/utils/news_util.dart';
import 'package:aichat_flutter_wallet/module_common/bridge/native_channel_bridge.dart';
import 'package:aichat_flutter_wallet/module_common/network/http_api.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/bottom_sheet_widget.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/easyloading.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:lib_network/http_manager.dart';
import 'package:lib_network/http_response.dart';
import 'package:lib_network/lib_network.dart';

import '../../../module_common/widgets/home_bar/home_bar.dart';



class CommemtTypeCallBackData{
  String content;
  List<String> videos;
  List<String> images;

  CommemtTypeCallBackData(
  {
    required this.content,
    required this.videos,
    required this.images,
});
}
class NewCommemtWidget extends StatefulWidget {
  String toName = '';
  VoidCallback?  closeCallback ;
  Function? onConfirm;
  NewCommemtWidget({Key? key, required this.toName,this.closeCallback= null, this.onConfirm})
      : super(key: key);

  @override
  _NewCommemtWidgetState createState() => _NewCommemtWidgetState();
}

class _NewCommemtWidgetState extends State<NewCommemtWidget> {
  TextEditingController controller = TextEditingController();
  String content = '';
  List<XFile> files = []; // 文件
  List<String> imgShowList = []; //  用来展示
  String uploadUrl = '';
  int selectType = 1;
  Dio? _dio;
  List<String> videos = [];
  List<String> images = [];

  @override
  void dispose() {
    /// 取消路由订阅
    super.dispose();
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }


  @override
  Widget build(BuildContext context) {
    return BottomSheetWidget(
      title: 'Comment',
      expand: false,
      closeCallback: widget.closeCallback,
      child: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              constraints: BoxConstraints(minHeight: 100.h),
              margin: EdgeInsets.only(left: 20.w, right: 20.w),
              padding: EdgeInsets.only(left: 15.w, right: 15.w),
              decoration: BoxDecoration(
                  color: AppColors.c_F6F6F6,
                  borderRadius: BorderRadius.circular(10)),
              child: TextField(
                controller: controller,
                autofocus: true,
                maxLength: 300,
                maxLines: 3,
                onChanged: (value) {
                  content = value;
                  setState(() {});
                },
                decoration: InputDecoration(
                    hintText: widget.toName.isEmpty?'':"@${widget.toName}",
                    border: InputBorder.none,
                    labelStyle:
                    TextStyle(fontSize: 14.sp, color: AppColors.c_333333),
                    hintStyle: TextStyle(
                        fontSize: 14.sp, color: AppColors.c_BEBDCA)),
              ),
            ),
            if (imgShowList.isNotEmpty)
              Container(
                margin: EdgeInsets.only(left: 20.w, top: 15.h),
                child: Container(
                  child: Stack(
                    clipBehavior: Clip.none,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10),
                        child: Image.file(
                          File(imgShowList[0]),
                          width: 106,
                          height: 106,
                          fit: BoxFit.cover,
                        ),
                      ),
                      if (selectType == 2)
                        Positioned(
                          left: 0,
                          top: 0,
                          right: 0,
                          bottom: 0,
                          child: Container(
                            alignment: Alignment.center,
                            child: PublicImage(
                              image: 'assets/images/common/commen_video.png',
                              width: 40,
                              height: 40,
                            ),
                          ),
                        ),
                      Positioned(
                          right: -5,
                          top: -5,
                          child: InkWell(
                            onTap: () {
                              imgShowList = [];
                              setState(() {});
                            },
                            child: PublicImage(
                              image: 'assets/images/common/phote_delete.png',
                              width: 20,
                              height: 20,
                            ),
                          )),
                    ],
                  ),
                ),
              ),
            Container(
              margin: EdgeInsets.only(left: 20.w, right: 20.w),
              height: 60.w,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  InkWell(
                    onTap: () async {
                      final ImagePicker picker = ImagePicker();
                      picker.pickMultipleMedia().then((value) async {
                        // 判断是视频还是图片
                        selectType = NewsUtil.getFileType(value[0].path);
                        files = value;
                        if (selectType == 2) {
                          imgShowList = [
                            await NewsUtil.getVideoPickerThumb(value[0].path)
                          ];
                        } else {
                          imgShowList = [value[0].path];
                        }
                        setState(() {});
                      });
                    },
                    child: PublicImage(
                      image: 'assets/images/common/photo.png',
                      width: 20.w,
                      height: 20.w,
                    ),
                  ),
                  if (content.isNotEmpty || files.isNotEmpty)
                    InkWell(
                      onTap: () async {
                        FocusScope.of(context).unfocus();
                        if (files.isEmpty) {
                          CommemtTypeCallBackData popRes = CommemtTypeCallBackData(
                            content: content,
                            videos: videos,
                            images: images,
                          );
                          if(widget.onConfirm!=null){
                            widget.onConfirm!(popRes).then((_) {
                              kaiPrint('desotry ');
                            });
                          }else{
                            Navigator.of(context).pop(popRes);
                          }
                        } else {
                          // 获取预签名链接
                          String date = NewsUtil.transCurDate();
                          String? uid =
                              NativeChannelBridge.instance.appCommMsg?.userId;
                          String fileName =
                              '/hj-global/bit-chat/${selectType}/${date}/1/${uid}/${files[0].name}';
                          BaseResp? res = await HttpManager().get(
                              '${API.getUploadUrl}?object_key=${fileName}',
                              {});
                          if (res!.code == 0) {
                            Map data = res.data;
                            uploadUrl = data['url'];
                            String allUploadUrl =
                            NewsUtil.removeQueryParameters(uploadUrl);
                            if (_dio == null) {
                              BaseOptions options = BaseOptions(
                                contentType: selectType == 1
                                    ? 'image/jpeg'
                                    : 'video/mp4',
                              );
                              _dio = Dio(options);
                            }
                            File file = File(files[0].path);
                            EasyLoading.generateLoadingFuture(_dio!.put(
                                uploadUrl,
                                data: await file.readAsBytes()))
                                .then((uploadRes) {
                              kaiPrint('res===${uploadRes}');
                              // 上传工程
                              if (uploadRes.statusCode == 200) {
                                // 获取完整文件路径
                                if (selectType == 1) {
                                  images = [allUploadUrl];
                                } else if (selectType == 2) {
                                  videos = [allUploadUrl];
                                }
                                CommemtTypeCallBackData popRes = CommemtTypeCallBackData(
                                  content: content,
                                  videos: videos,
                                  images: images,
                                );
                                // Navigator.of(context).pop(popRes);
                                if(widget.onConfirm!=null){
                                  widget.onConfirm!(popRes);
                                }else{
                                  Navigator.of(context).pop(popRes);
                                }
                              } else {
                                // 上传出错
                                images = [];
                                videos = [];
                                Toast.show(context,
                                    message:
                                    'file upload error! plese try again',
                                    status: '2');
                              }
                            });
                          }
                        }
                      },
                      child: Container(
                        decoration: BoxDecoration(
                            color: AppColors.c_8667FE,
                            borderRadius: BorderRadius.circular(10)),
                        padding: EdgeInsets.symmetric(
                            horizontal: 13.w, vertical: 8.w),
                        child: Text(
                          'Confirm',
                          style: TextStyle(fontSize: 12, color: Colors.white),
                        ),
                      ),
                    )
                ],
              ),
            ),
            HomeBar()
          ],
        ),
      ),
    );
  }
}
